package com.bocai.grainshop.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bocai.common.constant.AuthServerConstant;
import com.bocai.common.utils.HttpUtils;
import com.bocai.common.utils.R;
import com.bocai.common.vo.MemberVo;
import com.bocai.grainshop.authserver.feign.MemberfeignService;
import com.bocai.grainshop.authserver.vo.SocialUser;
import com.bocai.grainshop.authserver.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Controller
public class loginController {


    @Autowired
    private MemberfeignService memberfeignService;

    /**
     * @Author: SunJinbo
     * @Description  gitee登录
     * @Param []
     * @return java.lang.String
     * @Data Created in 2022/4/11 20:08
     */
    @GetMapping("/auth/gitee/success")
    public String giteeLogin(@RequestParam("code") String code, HttpSession session){
        Map<String,String > map = new HashMap<>();
        map.put("code",code);
        map.put("client_id","6ff78d483a57ff87fe489c625fb239b779ce71a22d1366509e0eaa0a4ff4eb79");
        map.put("redirect_uri","http://auth.grainshop.com/auth/gitee/success");
        map.put("client_secret","528bdaa3b155ca643100401942d99e9a8d069f6a1b737f229478124dc1118acc");
        map.put("grant_type","authorization_code");
        HttpResponse post = null;
        try {
            post = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(post!=null){
            //获取响应数据 封装带实体类中
            if(post.getStatusLine().getStatusCode() == 200){
                try {
                    String json = EntityUtils.toString(post.getEntity());
                    SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
                    //获取用户id https://gitee.com/api/v5/user
                    HttpResponse response = null;
                    try {
                        Map<String,String> m = new HashMap<>();
                        m.put("redirect_uri","http://auth.grainshop.com/auth/gitee/success");
                        //与openAPI文档不符  必须携带回调地址才能正确响应  否则报401错误
                        m.put("access_token",socialUser.getAccess_token());
                        response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get",
                                new HashMap<>(),m);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if(response!=null){
                        if(response.getStatusLine().getStatusCode() == 200){
                            String UserIdJson = EntityUtils.toString(response.getEntity());
                            log.info("1.----UserIdJson:{}"+UserIdJson);
                            JSONObject parseObject = JSON.parseObject(UserIdJson);
                            socialUser.setId(parseObject.getString("id"));
                            socialUser.setName(parseObject.getString("name"));
                            socialUser.setEmail(parseObject.getString("email"));
                        }
                    }
                    //判断用户是否第一次登录  是获取信息  不是注册信息
                    R r = memberfeignService.GiteeLogin(socialUser);
                    Object o = r.get("code");
                    String jsonO = JSON.toJSONString(o);
                    Integer codeNum = JSON.parseObject(jsonO, new TypeReference<Integer>() {
                    });
                    if(codeNum == 0){
                        Object user = r.get("user");
                        String userJSON = JSON.toJSONString(user);
                        MemberVo memberVo = JSON.parseObject(userJSON, MemberVo.class);
                        session.setAttribute(AuthServerConstant.LOGIN_USER,memberVo);
                        log.info("用户信息:{}"+memberVo);
                        return "redirect:http://grainshop.com/";
                    }else {

                        return "redirect:http://auth.grainshop.com/login";
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                return "redirect:http://auth.grainshop.com/login";
            }
        }
        return "redirect:http://auth.grainshop.com/login";
    }

    @PostMapping("/log")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes
    ,HttpSession session){
        R r = memberfeignService.loginMember(userLoginVo);
        Object code = r.get("code");
        String s = JSON.toJSONString(code);
        Integer CODE = JSON.parseObject(s, new TypeReference<Integer>() {
        });
        if(CODE == 0){
            //成功
            Object user = r.get("user");
            if(user!=null){
                String userJSON = JSON.toJSONString(user);
                MemberVo memberVo = JSON.parseObject(userJSON, MemberVo.class);
                session.setAttribute(AuthServerConstant.LOGIN_USER,memberVo);
            }
            return "redirect:http://grainshop.com/";
        }else {
            //失败
            Object msg = r.get("msg");
            String toJSONString = JSON.toJSONString(msg);
            String parseObject = JSON.parseObject(toJSONString, new TypeReference<String>() {
            });
            Map<String,String> map = new HashMap<>();
            map.put("msg",parseObject);
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.grainshop.com/login";
        }
    }

    /**
     * @Author: SunJinbo
     * @Description 微信登录  由于跨域不能保存 cookie 可以中保存  然后
     * 用 主域名 重新发请求查询数据库 设置cooike
     * @Param [code]
     * @return void
     * @Data Created in 2022/4/18 15:11
     */
    @GetMapping("/api/ucenter/wx/callback")
    public String WeiXinLogin(@RequestParam("code") String code){

        Map<String,String > map = new HashMap<>();
        map.put("code",code);
        map.put("appid","wxed9954c01bb89b47");
        map.put("secret","a7482517235173ddb4083788de60b90e");
        map.put("grant_type","authorization_code");

        HttpResponse post = null;
        try {
            post = HttpUtils.doPost("https://api.weixin.qq.com", "/sns/oauth2/" +
                    "access_token", "post", new HashMap<>(), map, new HashMap<>());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(post!=null){
            if(post.getStatusLine().getStatusCode() == 200){
                try {

                    String jsonS = EntityUtils.toString(post.getEntity());
                    SocialUser socialUser = JSON.parseObject(jsonS, SocialUser.class);
                    socialUser.setId(JSON.parseObject(jsonS).getString("openid"));
                    Map<String, String> m =  new HashMap<>();
                    m.put("access_token",socialUser.getAccess_token());
                    m.put("openid",socialUser.getId());
                    log.info("1-2{}"+socialUser.getAccess_token()+" "+socialUser.getId());

                    try {
                        HttpResponse get = HttpUtils.doGet("https://api.weixin.qq.com", "/sns/userinfo",
                                "GET", new HashMap<>(),
                                m);
                        if(get!=null && get.getStatusLine().getStatusCode() == 200){

                            String s = EntityUtils.toString(get.getEntity());
                            socialUser.setName("Hero");
                            //响应中文乱码问题
                            log.info("???{}"+JSON.parseObject(s).getString("nickname"));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    R r = memberfeignService.GiteeLogin(socialUser);
                    Object o = r.get("code");
                    String s = JSON.toJSONString(o);
                    Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
                    });

                    if(codeNum == 0){
                        Object user = r.get("user");
                        if(user != null){
                            String userJSON = JSON.toJSONString(user);
                            MemberVo memberVo = JSON.parseObject(userJSON, MemberVo.class);
                            log.info("{}"+memberVo.toString());

                          return "redirect:http://grainshop.com/";

                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:http://grainshop.com/";
    }

    @GetMapping("/login")
    public String BoolLogin(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute == null){
            return "login";
        }
        return "redirect:http://grainshop.com/";
    }

}
